package io.renren.modules.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.renren.common.utils.R;
import io.renren.modules.app.dao.ImGroupDao;
import io.renren.modules.app.dao.ImGroupUserDao;
import io.renren.modules.app.dao.ImMessageMapper;
import io.renren.modules.app.entity.*;
import io.renren.modules.app.service.IImMessageService;
import io.renren.modules.app.service.ImFriendService;
import io.renren.modules.app.service.UserService;
import io.renren.modules.app.tio.TioServerConfig;
import io.renren.modules.app.tio.WsOnlineContext;
import io.renren.modules.app.utils.ChatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.websocket.common.WsResponse;

import java.util.List;
import java.util.Map;

/**
 * 服务实现类
 *
 * @author 乐天
 * @since 2018-10-08
 */
@Service
@Qualifier(value = "iImMessageService")
public class ImMessageServiceImpl extends ServiceImpl<ImMessageMapper, ImMessage> implements IImMessageService {
    @Autowired
    private ImFriendService imFriendService;
    @Autowired
    private UserService userService;
    @Autowired
    private ImGroupDao imGroupDao;
    @Autowired
    private ImGroupUserDao imGroupUserDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveMessage(ImMessage imMessage) {
        new ImMessageServiceImpl.SaveChatMessageThread(imMessage).run();
    }

    @Override
    public R recall(UserEntity user, Message message) {
        message.setFrom_id(user.getUserId().toString());
        //发送信息
        SendInfo sendInfo = new SendInfo();
        sendInfo.setCode(ChatUtils.MSG_MESSAGE);
        sendInfo.setMessage(message);
        sendInfo.setMsg("recall");
        WsResponse wsResponse = null;
        try {
            wsResponse = WsResponse.fromText(new ObjectMapper().writeValueAsString(sendInfo), TioServerConfig.CHARSET);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        ChannelContext cco = WsOnlineContext.getChannelContextByUser(user.getUserId().toString());
        // 单聊
        if (message.getChat_type().equals("user")) {
            Tio.sendToUser(cco.groupContext, message.getTo_id(), wsResponse);
            return R.ok(message);
        }
        // 群聊
        ImGroupEntity ig = imGroupDao.selectOne(new QueryWrapper<ImGroupEntity>().eq("id",message.getTo_id()).eq("status",1));
        if(ig==null){

        }else {
            Tio.sendToGroup(cco.groupContext, message.getTo_id(), wsResponse);
        }
        return R.ok(message);
    }

    @Override
    public R send(UserEntity user, Message message) {
        if(message.getChat_type().equals("user")){
            // 验证好友是否存在，并且对方没有把你拉黑
            ImFriendEntity ifend = imFriendService.getOne(new QueryWrapper<ImFriendEntity>().eq("isblack", 0).eq("friend_id", user.getUserId()).eq("user_id",message.getTo_id()));
            if (ifend==null)return R.error("对方不存在或者已经把你拉黑");
            // 验证好友是否被禁用
            if((userService.getOne(new QueryWrapper<UserEntity>().eq("user_id", message.getTo_id()))).getStatus()!=0)return R.error("对方已被禁用");;
            Message msg = new Message();

        }
        return null;
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<ImMessage> getUnReadMessage(String toId) {
        QueryWrapper<ImMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("to_id", toId);
        queryWrapper.eq("read_status", "1");
        List<ImMessage> messageList = baseMapper.selectList(queryWrapper);
        for (ImMessage message : messageList) {
            message.setReadStatus(ChatUtils.READED);
            this.updateById(message);
        }
        return messageList;
    }


    /**
     * 内部类
     */
    class SaveChatMessageThread implements Runnable {

        private ImMessage imMessage;

        public SaveChatMessageThread(ImMessage imMessage) {
            this.imMessage = imMessage;
        }

        @Override
        public void run() {
            save(imMessage);
        }
    }
}
